package com.mucanghua.verticle;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.http.*;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;

public class WebServer extends AbstractVerticle {

    static {
        System.setProperty("vertx.disableDnsResolver", "true");
        System.setProperty("vertx.disableFileCaching", "true");
    }

    public static void main(String[] args) {
        DeploymentOptions deploymentOptions = new DeploymentOptions();
        deploymentOptions.setConfig(new JsonObject()
        .put("web_root", "D:\\work\\mucanghua\\pigx-ui\\dist"));
        Vertx.vertx().deployVerticle(WebServer.class.getName(), deploymentOptions);
    }

    private int port = 8888;
    private int api_port = 9999;

    @Override
    public void start() throws Exception {
        JsonObject config = config();
        if (config.getInteger("port") != null)
            port = config.getInteger("port");
        if (config.getInteger("api_port") != null)
            api_port = config.getInteger("api_port");

        String webRoot = config.getString("web_root");
        HttpServer httpServer = vertx.createHttpServer();

        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());

        WebClient webClient = WebClient.create(vertx, new WebClientOptions().setMaxPoolSize(100).setDefaultPort(api_port));

        router.routeWithRegex("^/(code|auth|admin|gen)(/?|/.*)").handler(ctx -> {
            HttpServerRequest request = ctx.request();
            HttpServerResponse response = ctx.response();
            webClient.request(request.method(), request.uri()).putHeaders(request.headers()).sendBuffer(ctx.getBody(), res -> {
                if (!response.closed()) {
                    if (res.succeeded()) {
                        response.setChunked(true);
                        response.setStatusCode(res.result().statusCode());
                        if (res.result().body() != null) {
                            response.write(res.result().body());
                        }
                        response.end();
                    } else {
                        response.end();
                    }
                }
            });
        });

        StaticHandler staticHandler = StaticHandler.create();
        staticHandler.setAllowRootFileSystemAccess(true);
        staticHandler.setWebRoot(webRoot);
        router.route().handler(staticHandler);

        httpServer.requestHandler(router).listen(port, ar -> {
            if (ar.succeeded()) {
                System.out.println("web server start succeed on : " + port);
            } else {
                System.out.println("web server start failed by " + ar.cause().getMessage());
            }
        });
    }
}
